/**
 * Copyright (c) 2020-2024, huli.com
 * All rights reserved.
 */
package com.xiaohujr.xuexue.leetcode.tree;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

/**
 * @author Xue Xue (xuexue1@huli.com)
 * @version 1.0
 * @since 2020/12/14
 */
public class Q589 {

    /**
     * 迭代法
     *
     * @param root
     * @return
     */
    public List<Integer> preorder(Node root) {
        LinkedList<Node> stack = new LinkedList<>();
        LinkedList<Integer> output = new LinkedList<>();
        if (root == null) {
            return output;
        }
        stack.add(root);
        while (!stack.isEmpty()) {
            Node node = stack.pollLast();
            output.add(node.val);
            Collections.reverse(node.children);
            for (Node item : node.children) {
                stack.add(item);
            }
        }
        return output;
    }

    public List<Integer> preorderSelf(Node root) {
        LinkedList<Node> stack = new LinkedList<>();
        List<Integer> result = new ArrayList<>();
        stack.add(root);
        while (!stack.isEmpty()) {
            Node pollNode = stack.pollLast();
            result.add(pollNode.val);
            Collections.reverse(pollNode.children);
            for (Node node : pollNode.children) {
                stack.add(node);
            }
        }
        return result;
    }

    List<Integer> rtnList = new ArrayList<>();

    /**
     * 递归法
     *
     * @param root
     * @return
     */
    public List<Integer> preorder1(Node root) {
        if (root == null) {
            return rtnList;
        }
        if (root.children == null) {
            rtnList.add(root.val);
            return rtnList;
        }
        rtnList.add(root.val);
        for (Node node : root.children) {
            preorder1(node);
        }

        return rtnList;
    }

    public static void main(String[] args) {
        List<Node> child3 = new ArrayList<>();
        child3.add(new Node(5));
        child3.add(new Node(6));
        Node node21 = new Node(3, child3);
        List<Node> child2 = new ArrayList<>();
        child2.add(node21);
        child2.add(new Node(2));
        child2.add(new Node(4));
        Node root = new Node(1, child2);

        System.out.println(new Q589().preorder1(root));
    }

}
